package com.epfly.promo.activity.impl.discount.predicate;

import com.epfly.base.util.DateUtil;
import com.epfly.promo.activity.dao.ActivityDayBoundMapper;
import com.epfly.promo.activity.dao.UserActivityDayStatisticsMapper;
import com.epfly.promo.activity.entity.ActivityDayBoundEntity;
import com.epfly.promo.activity.entity.ActivityEntity;
import com.epfly.promo.activity.entity.UserActivityDayStatisticsEntity;
import com.epfly.promo.activity.impl.discount.ActivityWrapper;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 日限额限次过滤
 */
@Order(value = PredicateOrder.BOUND_DAY_ORDER)
@Service
public class BoundDayPredicate implements ActivityDiscountPredicate {

    @Resource
    private ActivityDayBoundMapper activityDayBoundMapper;

    @Resource
    private UserActivityDayStatisticsMapper userActivityDayStatisticsMapper;

    @Resource
    private BoundPredicateHelper boundPredicateHelper;

    @Override
    public boolean test(ActivityWrapper activityWrapper) {

        if (boundPredicateHelper.assertBasic(activityWrapper)) {
            return true;
        }

        ActivityEntity activityEntity = activityWrapper.getActivityEntity();
        // 订单时间
        Long orderTime = activityWrapper.getOrderTime();
        // 根据订单时间计算日期
        Integer day = DateUtil.getDateByProvidedTime(orderTime);
        // 用户ID
        String userID = activityWrapper.getUserID();

        ActivityDayBoundEntity dayBoundEntity = activityDayBoundMapper.findByActivityId(activityEntity.getId());

        if (boundPredicateHelper.assertBoundBasic(dayBoundEntity)) {
            return true;
        }

        UserActivityDayStatisticsEntity dayStatistics = userActivityDayStatisticsMapper.findByUserIdAndActivityIdAndDay(userID, activityEntity.getId(), day);

        return boundPredicateHelper.assertBoundRule(dayStatistics, dayBoundEntity);
    }

}
